﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;

namespace DingHelper
{
    public class DingApiHelper
    {
        /// <summary>
        /// 钉钉Secret
        /// </summary>
        private string dDSecret = string.Empty;

        /// <summary>
        /// 钉钉的webHook地址
        /// </summary>
        private string webHookUrl = string.Empty;

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="secret">钉钉Secret，机器人设置加签处获取</param>
        /// <param name="webHook">机器人设置完成的Webhook地址</param>
        public DingApiHelper(string secret, string webHook)
        {
            dDSecret = secret;
            webHookUrl = webHook;
        }

        /// <summary>
        /// 发送钉钉通知
        /// </summary>
        /// <param name="msg">内容</param>
        public bool SendNotify(string msg)
        {
            try
            {
                string timestamp = ((DateTime.Now.Ticks - TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)).Ticks) / 10000).ToString();

                string stringToSign = $"{timestamp}\n{dDSecret}";

                string hmac_code = GetHash(stringToSign, dDSecret);

                string sign = System.Web.HttpUtility.UrlEncode(hmac_code, Encoding.UTF8);

                //消息类型
                var msgtype = MsgTypeEnum.text.ToString();

                //文本内容
                var text = new Text
                {
                    Content = msg
                };

                //指定目标人群
                var at = new At()
                {
                    AtMobiles = new List<string>() { },
                    IsAtAll = false
                };


                string url = $"{webHookUrl}&sign={sign}&timestamp={timestamp}";
                using (HttpClient httpClient = new HttpClient())
                {
                    HttpContent content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(new
                    {
                        msgtype,
                        text,
                        at
                    }));
                    content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                    HttpResponseMessage response = httpClient.PostAsync(url, content).Result;
                    string html = response.Content.ReadAsStringAsync().Result;
                }
                return true;

            }
            catch(Exception ex)
            {
                return false;
            }
        }


        public string GetHash(string text, string key)
        {
            ASCIIEncoding encoding = new ASCIIEncoding();

            byte[] textBytes = encoding.GetBytes(text);
            byte[] keyBytes = encoding.GetBytes(key);

            byte[] hashBytes;

            using (HMACSHA256 hash = new HMACSHA256(keyBytes))
                hashBytes = hash.ComputeHash(textBytes);

            return Convert.ToBase64String(hashBytes);
        }

    }

    /// <summary>
    /// 钉钉群机器人消息类型枚举
    /// </summary>
    public enum MsgTypeEnum
    {
        text,
        link,
        markdown,
        actionCard,
        feedCard
    }

    /// <summary>
    /// 文本类型
    /// </summary>
    public class Text
    {
        /// <summary>
        /// 文本内容
        /// </summary>
        [JsonProperty(PropertyName = "content")]
        public string Content { get; set; }
    }

    /// <summary>
    /// @指定人
    /// </summary>
    public class At
    {
        /// <summary>
        /// @的联系人
        /// </summary>
        [JsonProperty(PropertyName = "atMobiles")]
        public List<string> AtMobiles { set; get; }

        /// <summary>
        /// 是否@所有人
        /// </summary>
        [JsonProperty(PropertyName = "isAtAll")]
        public bool IsAtAll { set; get; }
    }
}
